package com.hdlang.assists.ad.app

import android.app.Application
import com.getkeepsafe.relinker.ReLinker
import com.hdlang.assists.ad.utils.LogUtils
import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKVContentChangeNotification
import com.tencent.mmkv.MMKVHandler
import com.tencent.mmkv.MMKVLogLevel
import com.tencent.mmkv.MMKVRecoverStrategic
import java.io.File

class App : Application(), MMKV.LibLoader, MMKVHandler, MMKVContentChangeNotification {

    override fun onCreate() {
        super.onCreate()
        val dir = filesDir.absoluteFile.toString() + File.separator + "mmkv"
        val rootDir = MMKV.initialize(this, dir, this, MMKVLogLevel.LevelInfo, this)
        MMKV.registerContentChangeNotify(this)
    }

    override fun loadLibrary(libName: String?) {
        if (libName?.isNotEmpty() == true) {
            ReLinker.loadLibrary(this, libName)
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        MMKV.onExit()
    }

    override fun onMMKVCRCCheckFail(mmapID: String?): MMKVRecoverStrategic =
        MMKVRecoverStrategic.OnErrorRecover


    override fun onMMKVFileLengthError(mmapID: String?): MMKVRecoverStrategic =
        MMKVRecoverStrategic.OnErrorRecover


    override fun wantLogRedirecting(): Boolean = true

    override fun mmkvLog(level: MMKVLogLevel?, file: String?, line: Int,
                         func: String?, message: String?) {
        val log = "<$file:$line::$func> $message"
        LogUtils.d(log)
    }

    override fun onContentChangedByOuterProcess(mmapID: String?) {
    }
}